Server-Sent Events
#HTTP #Web #JavaScript
サーバからクライアントに向けてプッシュで情報を送信できる非同期通信
HTTP/1.1を利用して通信を行う
サーバ側は Content-Type: text/event-stream というヘッダを付けて送信する
クライアント側は、JavaScriptであれば EventSource インタフェースを用いてデータを受け取る
WebSocketと比較したときに、HTTPを利用するため互換性は高いが、パフォーマンスは劣る
最近、OpenAI APIをはじめとした大規模言語モデルのAPIでの採用事例が多い
https://html.spec.whatwg.org/multipage/server-sent-events.html
https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events
https://developer.mozilla.org/en-US/docs/Web/API/EventSource
JavaScriptクライアント
code:js
const eventSource = new EventSource('/api/sse');
eventSource.addEventListener('heck', (event) => {
console.log(event.data);
});
Node.js Fastify
Node.js Fastifyでは、fastify-sse-v2というモジュールを使うのが良いらしい
https://github.com/mpetrunic/fastify-sse-v2
code:js
import { FastifySSEPlugin } from 'fastify-sse-v2';
const server = fastify();
server.register(FastifySSEPlugin);
server.get('/api/sse', async (req, res) => {
for (let i = 0; i < 10; i ++) {
await sleep(1000);
res.sse({
event: 'heck',
data: Math.random().toFixed(6),
});
}
});